#!/bin/sh
. /etc/utils.sh

# mcnmp_server is needed only on TV Box
! is-tv-box && exit 0

case "$1" in
  start)
    (
      # mcnmp_server playback code needs widevine and pullreader .so
      export LD_LIBRARY_PATH=/app/client
      export SAGEBIN_PATH=/usr/lib/sage_firmware
      export DRM_BIN_FILE=/user/widevine/drm.bin
      rm -f /tmp/nexus_multiprocess
      babysit 10 mcnmp_server 2>&1 | logos mcnmp_server 0 20000000 &
      wait-until-created /tmp/nexus_multiprocess
      # This waits will we can connect to the mcnmp_server.
      mcnmp_retries=0
      while [ "$mcnmp_retries" -lt "60" ] && \
          ! ( nc 127.0.0.1 6167 < /dev/null ) ; do
        sleep 1
        mcnmp_retries=$((mcnmp_retries+1))
      done
      # Before we let the world know we are ready, check and re-initialize
      # PlayReady and Widevine if necessary.
      /app/client/verify_playready_widevine | logos mcnmp_server
      touch /tmp/mcnmp_ready
      if is-secure-boot; then
        : >/tmp/gpio/ledcontrol/secure_boot
      else
        rm -f /tmp/gpio/ledcontrol/secure_boot
      fi
      nice babysit 60 irmon 2>&1 | logos irmon &
    ) &
    ;;
  stop)
    pkillwait -x startupvideo  # if it's running, prevents miniclient from starting up
    pkillwait -x irmon
    pkillwait -x mcnmp_server
    ;;
  restart)
    $0 stop; $0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac
